// pages/car/car.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    carList: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    db.collection('mock_car').watch({
      onChange: (res) => {
        this.setData({
          carList: res.docs.map(item => {
            return {
              ...item,
              checked: this.data.carList.find(ite => ite._id === item._id )?.checked || false
            }
          })
        })
      },
      onError: (err) => {}
    })
  },

  onChange(e) {
    const {id} = e.currentTarget.dataset;
    db.collection('mock_car').doc(id).update({
      data: {
        count: e.detail
      }
    })
  },

  checkItem(e) {
    const {id} = e.currentTarget.dataset;

    this.setData({
      carList: this.data.carList.map(item => {
        return {
          ...item,
          checked: item._id === id ? !!e.detail.value.length : item.checked
        }
      })
    })
  },
  checkAll(e) {
    const checked = !!e.detail.value.length;
    this.setData({
      carList: this.data.carList.map(item => ({...item,checked}))
    },(res) => {
      console.log(this.data.carList)
    })
  }
})